package com.gx.auth.common.tree;

import com.gx.auth.entity.Function;

import java.util.*;

/**
 * Created by gx on 2017/4/3.
 */
public class Tree {
    private List<Node> nodes = new LinkedList<>();
    private Node root = null;

    public Tree(List<Function> functions) {
        for (Function function : functions){
            Node node = new Node(function.getId(),function.getParentId(),
                                function.getName(),"open",
                                new NodeAttribute(null == function.getUrl() ?"":function.getUrl(),function.getId()),
                                function.getSerialNum());
            nodes.add(node);
            if (node.getId() == 0){
                root = node;
            }
        }
    }
    public List<Node> build(){
        buildTree(root);
        List<Node> result = new ArrayList<Node>();
        result.add(root);
        return result;
    }
    public void buildTree(Node parent){
        Node node = null;
        for (Iterator<Node> iterator =nodes.iterator();iterator.hasNext();){
            node= iterator.next();
            if (Objects.equals(node.getParentId(),parent.getId())){
                parent.getChildren().add(node);
                buildTree(node);
            }
        }

    }
}
